package com.examstack.management.controller.page.admin;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.examstack.common.domain.exam.ExamPaper;
import com.examstack.common.domain.question.*;
import com.examstack.common.util.DateUtil;
import com.examstack.management.service.ExamPaperService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.examstack.common.util.Page;
import com.examstack.common.util.PagingUtil;
import com.examstack.common.util.QuestionAdapter;
import com.examstack.management.security.UserInfo;
import com.examstack.management.service.QuestionService;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class QuestionPageAdmin {
	
	@Autowired
	private QuestionService questionService;

	@Autowired
	private ExamPaperService examPaperService;
	
	@RequestMapping(value = "/admin/question/question-list", method = RequestMethod.GET)
	public String questionListPage(Model model) {

		return "redirect:question-list/filter-0-0-0-0-0-0-0-1.html";
	}
	
	@RequestMapping(value = "/admin/question/question-list/filter-{fieldId}-{knowledge}-{questionType}-{tag}-{status}-{difficulty}-{searchParam}-{page}.html", method = RequestMethod.GET)
	public String questionListFilterPage(Model model,
			@PathVariable("fieldId") int fieldId,
			@PathVariable("knowledge") int knowledge,
			@PathVariable("questionType") int questionType, @PathVariable("difficulty") int difficulty,
			@PathVariable("tag") int tag, @PathVariable("status") int status,
			@PathVariable("searchParam") String searchParam,
			@PathVariable("page") int page) {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		QuestionFilter qf = new QuestionFilter();
		qf.setFieldId(fieldId);
		qf.setKnowledge(knowledge);
		qf.setQuestionType(questionType);
		qf.setTag(tag);
		qf.setStatus(status);
		qf.setDifficulty(difficulty);
		if (searchParam.equals("0"))
			searchParam = "-1";
		qf.setSearchParam(searchParam);

		Page<Question> pageModel = new Page<Question>();
		pageModel.setPageNo(page);
		pageModel.setPageSize(15);

		List<Question> questionList = questionService.getQuestionList(
				pageModel, qf);

		String pageStr = PagingUtil.getPageBtnlinkWithTotal(page,
				pageModel.getTotalPage(),pageModel.getTotalRecord());

		List<Field> fieldList = questionService.getAllField(null);
		model.addAttribute("fieldList", fieldList);

		/*if(fieldList.size() > 0)
			fieldId = fieldList.get(0).getFieldId();*/
		model.addAttribute("knowledgeList",
				questionService.getKnowledgePointByFieldId(fieldId,null));

		model.addAttribute("questionTypeList",
				questionService.getQuestionTypeList());

		model.addAttribute("questionFilter", qf);
		model.addAttribute("questionList", questionList);
		
		model.addAttribute("pageStr", pageStr);
		model.addAttribute("tagList", questionService.getTags(null));
		//保存筛选信息，删除后跳转页面时使用
		model.addAttribute("fieldId", fieldId);
		model.addAttribute("knowledge", knowledge);
		model.addAttribute("questionType", questionType);
		model.addAttribute("searchParam", "-1".equals(searchParam)?"":searchParam);

		//新增试题状态查询条件
		Status statusObject=new Status();
		List<Status> statusList=statusObject.getStatusList();
		model.addAttribute("statusList", statusList);

		//新增试题状态查询条件
		Difficulty difficultyObject=new Difficulty();
		List<Difficulty> difficultyList=difficultyObject.getStatusList();
		model.addAttribute("difficultyList", difficultyList);

		return "question-list";
	}
	
	/**
	 * 题库页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/admin/question/question-list/filterdialog-{examPaperId}-{fieldId}-{knowledge}-{questionType}-{searchParam}-{page}.html", method = RequestMethod.GET)
	public String questionListFilterDialogPage(Model model,
			@PathVariable("examPaperId") int examPaperId,
			@PathVariable("fieldId") int fieldId,
			@PathVariable("knowledge") int knowledge,
			@PathVariable("questionType") int questionType,
			@PathVariable("searchParam") String searchParam,
			@PathVariable("page") int page) {

		ExamPaper examPaper = examPaperService.getExamPaperById(examPaperId);
		List<String> idLIst=new ArrayList<String>();
		if(examPaper.getContent() != null && !examPaper.getContent().equals("")){
			Gson gson = new Gson();
			List<QuestionQueryResult> questionList = gson.fromJson(examPaper.getContent(), new TypeToken<List<QuestionQueryResult>>(){}.getType());
			for(QuestionQueryResult question : questionList){
				idLIst.add(String.valueOf(question.getQuestionId()));
			}
		}
		
		QuestionFilter qf = new QuestionFilter();
		qf.setIdList(idLIst);
		qf.setFieldId(fieldId);
		qf.setKnowledge(knowledge);
		qf.setQuestionType(questionType);
		if (searchParam.equals("0"))
			searchParam = "-1";
		qf.setSearchParam(searchParam);

		Page<Question> pageModel = new Page<Question>();
		pageModel.setPageNo(page);
		pageModel.setPageSize(10);

		List<Question> questionList = questionService.getQuestionList(
				pageModel, qf);

		String pageStr = PagingUtil.getPageBtnlinkWithTotal(page,
				pageModel.getTotalPage(),pageModel.getTotalRecord());

		model.addAttribute("fieldList", questionService.getAllField(null));

		model.addAttribute("knowledgeList",
				questionService.getKnowledgePointByFieldId(fieldId,null));

		model.addAttribute("questionTypeList",
				questionService.getQuestionTypeList());

		model.addAttribute("questionFilter", qf);
		model.addAttribute("questionList", questionList);
		model.addAttribute("pageStr", pageStr);
		
		//保存筛选信息，删除后跳转页面时使用
		model.addAttribute("examPaperId", examPaperId);
		model.addAttribute("fieldId", fieldId);
		model.addAttribute("knowledge", knowledge);
		model.addAttribute("questionType", questionType);
		model.addAttribute("searchParam", searchParam);
		model.addAttribute("tagList", questionService.getTags(null));
		return "question-list-dialog";
	}
	
	/**
	 * 添加试题页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/admin/question/question-add", method = RequestMethod.GET)
	public String questionAddPage(Model model) {
		List<Field> fieldList = questionService.getAllField(null);
		model.addAttribute("fieldList", fieldList);
		return "question-add";
	}
	
	/**
	 * 试题导入页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/admin/question/question-import", method = RequestMethod.GET)
	public String questionImportPage(Model model) {
		
		List<Field> fieldList = questionService.getAllField(null);
		model.addAttribute("fieldList", fieldList);
		return "question-import";
	}
	
	@RequestMapping(value = "/admin/question/question-preview/{questionId}", method = RequestMethod.GET)
	public String questionPreviewPage(Model model,
			@PathVariable("questionId") int questionId, HttpServletRequest request){
		String strUrl = "http://" + request.getServerName() //服务器地址  
                + ":"   
                + request.getServerPort() + "/";
		Question question = questionService.getQuestionByQuestionId(questionId);
		List<Integer> idList = new ArrayList<Integer>();
		idList.add(questionId);
		List<QuestionQueryResult> questionQueryList = questionService.getQuestionDescribeListByIdList(idList);
		HashMap<Integer, QuestionQueryResult> questionMap = new HashMap<Integer, QuestionQueryResult>();
		for (QuestionQueryResult qqr : questionQueryList) {
			if (questionMap.containsKey(qqr.getQuestionId())) {
				QuestionQueryResult a = questionMap.get(qqr.getQuestionId());
				questionMap.put(qqr.getQuestionId(), a);
			} else {
				questionMap.put(qqr.getQuestionId(), qqr);
			}
		}
		QuestionAdapter adapter = new QuestionAdapter(question,null,questionMap.get(questionId),strUrl);
		String strHtml = adapter.getStringFromXML(true, false, true);
		model.addAttribute("strHtml", strHtml);
		model.addAttribute("question", question);
		return "question-preview";
	}

	/**
	 * 试题统计
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/admin/question/question-count/{status}-{page}", method = RequestMethod.GET)
	private String examPaperListPage(Model model,
		 @RequestParam(value="createStart",required=false) String createStartTep,
		 @RequestParam(value="createStop",required=false) String createStopTep,
									 @PathVariable(value="status") Integer status,
		 @RequestParam(value="searchStr",required=false,defaultValue="") String searchStr, @PathVariable(value="page") Integer page){

		Page<QuestionUser> pageModel = new Page<QuestionUser>();
		pageModel.setPageNo(page);
		pageModel.setPageSize(8);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date createStart = new Date();
		Date createStop = new Date();
		try {
			if(createStartTep==null){
				createStart=DateUtil.getCurrYearFirst();
			}else{
				createStart=format.parse(createStartTep);
			}
			if(createStopTep==null){
				createStop=new Date();
			}else{
				createStop=format.parse(createStopTep);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		List<QuestionUser> questionUserList = questionService.getQuestionUserList(status,searchStr,createStart,createStop,pageModel);

		String pageStr = PagingUtil.getPageBtnlinkWithTotal(page, pageModel.getTotalPage(), pageModel.getTotalRecord());


		String createStartStr = format.format(createStart);
		String createStopStr = format.format(createStop);
		model.addAttribute("status", status);
		//新增试题状态查询条件
		Status statusObject=new Status();
		List<Status> statusList=statusObject.getStatusList();
		model.addAttribute("statusList", statusList);
		model.addAttribute("createStart", createStartStr);
		model.addAttribute("createStop", createStopStr);
		model.addAttribute("questionUserList", questionUserList);
		model.addAttribute("pageStr", pageStr);
		model.addAttribute("searchStr", searchStr);
		return "question-count";
	}
}
